package com.zg.webSocket;

import com.alibaba.fastjson2.JSON;
import com.zg.domain.DataForClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Component
@ServerEndpoint("/websocket")
public class SendAllMsg {

    private static AtomicInteger onlineClient = new AtomicInteger(0);
    private static CopyOnWriteArraySet<SendAllMsg> socket = new CopyOnWriteArraySet<>();

    /**
     * 与某个客户端通信需要使用的
     * 发送数据
     */
    private Session session;


    /**
     * 连接成功回调
     */
    @OnOpen
    public void open(Session session){
        this.session = session;
        socket.add(this);
        onlineClient.incrementAndGet();
        try {
            HashMap<String, Object> map = new HashMap<>();
            map.put("online",onlineClient.get());
            SendAllMsg.sendInfo(map);
            sendMessage(DataForClient.getOnlineMap().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("websocket客户端连接：session：{}，在线数量:{}",session,onlineClient.get());
    }


    @OnClose
    public void close(Session session){
        socket.remove(this);
        onlineClient.decrementAndGet();
        HashMap<String, Object> map = new HashMap<>();
        map.put("online",onlineClient.get());
        SendAllMsg.sendInfo(map);
        log.info("websocket用户退出了，在线人数：{}",onlineClient.get());
    }

    @OnMessage
    public void receiveMessages(String message,Session session) throws Exception {
        if (message !=null && !message.isEmpty()){
            for (SendAllMsg sendAllMsg : socket) {
                sendAllMsg.sendMessage(message);
            }
        }
        log.info("websocket接收到消息：{}",message);
    }

    @OnError
    public void error(Throwable throwable){
        log.info("err");
        throwable.printStackTrace();
    }

    public void sendMessage(String message) throws Exception{
        synchronized (session){
            this.session.getBasicRemote().sendText(message);
        }
    }


    public static void sendInfo(Object message){
        if (CollectionUtils.isEmpty(socket)){
            return;
        }
        if (Objects.isNull(message)){
            return;
        }

        String s = JSON.toJSONString(message);

        for (SendAllMsg sendAllMsg : socket) {
            try {
                sendAllMsg.sendMessage(s);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
